def getMeta(String app="${JOB_NAME}") {

    log.debug("app = ${app}")

    def params = new com.cicd.AppMeta().getMeta(app)

    if (params != null) {
        lang = params.get('lang')
        log.debug("${app} 查找结果 : ${params}")
    }

    log.debug("lang : ${lang}")

    switch (lang) {
        case "java":
            pipeline_java(params)
        default:
            println "nice to meet you"
    }

}

def call() {

    def map = new com.cicd.AppMeta().getMeta("${JOB_NAME}")

    pipeline {
        agent any

        options {
            buildDiscarder(logRotator(numToKeepStr: '50'))
            disableConcurrentBuilds()
            timeout(time: 20, unit: 'MINUTES')
        }

        environment {
            JAR_PATH = map.get("artifact")
            GIT_URL = "git@gitee.com:mmbluex/happy-api.git"
            IMAGE_NAME = "swr.cn-north-4.myhuaweicloud.com/sysy-devops/${env.JOB_NAME}:${env.BUILD_NUMBER}"
        }


        parameters {
            choice(name: 'BUILD_ENV', choices: 'dev\ntest\nuat', description: '请选择部署环境:')
            choice(name: 'RUNTIME', choices: 'default\ndocker', description: '请选择运行环境:')
            gitParameter(branchFilter: 'origin/(.*)', defaultValue: 'master', name: 'BUILD_BRANCH', type: 'PT_BRANCH', description: '请选择分支:', useRepository: "${env.GIT_URL}")
        }

        stages {

            stage('1.拉取代码') {
                steps {
                    cleanWs()
                    echo "JAR_PATH = ${env.JAR_PATH}"
                    echo "部署环境:${params.BUILD_ENV}\n 运行环境: ${params.RUNTIME}\n 代码分支：${params.BUILD_BRANCH}"
                    git branch: 'master', credentialsId: 'ssh', url: "${env.GIT_URL}"
                }
            }

            stage('2. Build') {
                steps {
                    script {
                        configFileProvider([configFile(fileId: 'settings', variable: 'MAVEN_SETTINGS')]) {
                            docker.image('docker.m.daocloud.io/maven:3-jdk-8-alpine').inside("-v /root/.m2:/root/.m2") {
                                sh "mvn -s $MAVEN_SETTINGS clean package -Dmaven.test.skip=true"
                            }
                        }
                    }
                }
            }


            stage('3.Images') {
                steps {
                    script {
                        configFileProvider([configFile(fileId: 'Dockerfile', variable: 'dockerfile')]) {
                            docker.withRegistry("https://swr.cn-north-4.myhuaweicloud.com", "harbor") {
                                def app = docker.build("${env.IMAGE_NAME}", "--build-arg JAR_PATH=${env.JAR_PATH} --build-arg JAR_NAME=${env.JOB_NAME} . -f ${dockerfile}")
                                app.push()
                            }
                            sh "docker rmi -f ${env.IMAGE_NAME}"
                        }
                    }
                }
            }

            stage('4.Ansible') {
                steps {
                    script {
                        docker.image('alpine/ansible:2.18.6').inside('-e ANSIBLE_HOST_KEY_CHECKING=False -e ANSIBLE_DEPRECATION_WARNINGS=False -e ANSIBLE_PYTHON_INTERPRETER=auto_legacy_silent') {

                            checkout([
                                    $class: 'GitSCM',
                                    branches: [[name: "*/master"]],
                                    doGenerateSubmoduleConfigurations: false,
                                    extensions: [
                                            [$class: 'RelativeTargetDirectory', relativeTargetDir: 'devops']
                                    ],
                                    submoduleCfg: [],
                                    userRemoteConfigs: [[credentialsId: 'ssh',
                                                         url: 'git@gitee.com:mmbluex/ansible.git']]
                            ])
                            sh "pwd"
                            sh "ls -lh"

                            sh "cd devops && ls -lh"
                            sh "env"
                            echo "${WORKSPACE}"

                            dir ("${WORKSPACE}/devops") {
                                ansiColor('xterm') {
                                    ansiblePlaybook(
                                            playbook: 'playbook.yaml',
                                            inventory: "hosts/${params.BUILD_ENV}.ini",
                                            credentialsId: 'ssh',
                                            hostKeyChecking: false,
                                            colorized: true,
                                            extraVars: [
                                                    app     : [value: "${env.JOB_NAME}", hidden: false],
                                                    jar_path   : [value: "${env.JAR_PATH}", hidden: true],
                                                    lang   : [value: "java", hidden: true],
                                                    runtime   : [value: "${params.RUNTIME}", hidden: false],
                                                    image: [value: "${env.IMAGE_NAME}", hidden: false]
                                            ]
                                    )
                                }
                            }


                        }

                    }

                }
            }




        }

    }

}



def dingding() {
    def ds = new Date().format("yyyy-MM-dd HH:mm:ss")
    def userName = currentBuild.getBuildCauses()[-1].userName
    println(userName)
    def patchOrg = """
        {
            "msgtype": "link", 
            "link": {
                "title": "【DEV】环境 happy-api 构建成功",
                "text": "构建编号：${BUILD_NUMBER}
构建人：${currentBuild.getBuildCauses()[-1].userName}
构建时间：${ds}", 
                "picUrl": "http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/sign-check-icon.png", 
                "messageUrl": "${BUILD_URL}"
            }
        }
    """

    def response = httpRequest(
            url: "https://oapi.dingtalk.com/robot/send?access_token=4915fc672beb1fdf12a1a8b30a1f6ea9932537708c09d238f40034d42d627e9b",
            httpMode: 'POST',
            requestBody: patchOrg,
            contentType: 'APPLICATION_JSON_UTF8'
    )
    println('Status: '+response.status)
    println('Response: '+response.content)
}